import Exif from "exif-js";

//blob类型
export function blob2DataURI(blob, callback) {
  const reader = new FileReader();
  reader.onload = function (e) {
    callback(e.target.result);
  };
  reader.readAsDataURL(blob);
}
//base64转为文件
export function base64ToFile(urlData, fileName) {
  const arr = urlData.split(",");
  const mime = arr[0].match(/:(.*?);/)[1];
  const bytes = atob(arr[1]); // 解码base64
  let n = bytes.length;
  const ia = new Uint8Array(n);
  while (n--) {
    ia[n] = bytes.charCodeAt(n);
  }
  return new File([ia], `${fileName}.png`, { type: mime });
}
//图片转base64
export function imgUrl2Base64(imgURL, callback) {
  const img = new Image();
  img.setAttribute("crossOrigin", "anonymous");
  img.src = imgURL;
  const that = this;
  img.onload = () => {
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const context = canvas.getContext("2d");
    context.drawImage(img, 0, 0, img.width, img.height);
    callback(canvas.toDataURL("image/jpeg"), 0.9);
  };
}

//UrlData压缩后的图片
export function base64UrlData2Bolb(UrlData) {
  const data = window.atob(UrlData.split(",")[1]);
  const ia = new Uint8Array(data.length);
  for (let i = 0;i < data.length;i++) {
    ia[i] = data.charCodeAt(i);
  }
  const blob = new Blob([ia], {
    type: "image/jpeg",
  });
  //fd.append('file',blob, Date.now() + '.jpg');
  return blob;
}

//file文件图片压缩
export function imgPreview(file, maxsize, callback) {
  let Orientation;
  //去获取拍照时的信息，解决拍出来的照片旋转问题
  Exif.getData(file, function () {
    Orientation = Exif.getTag(this, "Orientation");
  });
  // 看支持不支持FileReader
  if (!file || !window.FileReader) return;
  if (/^image/.test(file.type)) {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      const result = this.result;
      const img = new Image();
      img.src = result;
      //判断图片是否大于MaxSize(Kb),反之压缩图片
      maxsize = 300;
      if (this.result.length <= maxsize * 1024) {
        callback(this.result);
      } else {
        img.onload = function () {
          const data = compress(img, Orientation);
          callback(data);
        };
      }
    };
  }
}

//图片 旋转方向 canvas
function rotateImg(img, direction, canvas) {
  //最小与最大旋转方向，图片旋转4次后回到原方向
  const min_step = 0;
  const max_step = 3;
  if (img == null) return;
  //img的高度和宽度不能在img元素隐藏后获取，否则会出错
  const height = img.height;
  const width = img.width;
  let step = 2;
  if (step == null) {
    step = min_step;
  }
  if (direction == "right") {
    step++;
    //旋转到原位置，即超过最大值
    step > max_step && (step = min_step);
  } else {
    step--;
    step < min_step && (step = max_step);
  }
  //旋转角度以弧度值为参数
  const degree = (step * 90 * Math.PI) / 180;
  const ctx = canvas.getContext("2d");
  switch (step) {
    case 0:
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(img, 0, 0);
      break;
    case 1:
      canvas.width = height;
      canvas.height = width;
      ctx.rotate(degree);
      ctx.drawImage(img, 0, -height);
      break;
    case 2:
      canvas.width = width;
      canvas.height = height;
      ctx.rotate(degree);
      ctx.drawImage(img, -width, -height);
      break;
    case 3:
      canvas.width = height;
      canvas.height = width;
      ctx.rotate(degree);
      ctx.drawImage(img, -width, 0);
      break;
  }
}

//图片 压缩
export function compress(img, Orientation) {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d") as any;
  //瓦片canvas
  const tCanvas = document.createElement("canvas");
  const tctx = tCanvas.getContext("2d") as any;
  const initSize = img.src.length;
  let width = img.width;
  let height = img.height;
  //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
  let ratio;
  if ((ratio = (width * height) / 4000000) > 1) {
    console.log("大于400万像素");
    ratio = Math.sqrt(ratio);
    width /= ratio;
    height /= ratio;
  } else {
    ratio = 1;
  }
  canvas.width = width;
  canvas.height = height;
  //        铺底色
  ctx.fillStyle = "#fff";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  //如果图片像素大于100万则使用瓦片绘制
  let count;
  if ((count = (width * height) / 1000000) > 1) {
    console.log("超过100W像素");
    count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
    //            计算每块瓦片的宽和高
    const nw = ~~(width / count);
    const nh = ~~(height / count);
    tCanvas.width = nw;
    tCanvas.height = nh;
    for (let i = 0;i < count;i++) {
      for (let j = 0;j < count;j++) {
        tctx.drawImage(
          img,
          i * nw * ratio,
          j * nh * ratio,
          nw * ratio,
          nh * ratio,
          0,
          0,
          nw,
          nh
        );
        ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
      }
    }
  } else {
    ctx.drawImage(img, 0, 0, width, height);
  }
  //修复ios上传图片的时候 被旋转的问题
  if (Orientation != "" && Orientation != 1) {
    switch (Orientation) {
      case 6: //需要顺时针（向左）90度旋转
        rotateImg(img, "left", canvas);
        break;
      case 8: //需要逆时针（向右）90度旋转
        rotateImg(img, "right", canvas);
        break;
      case 3: //需要180度旋转
        rotateImg(img, "right", canvas); //转两次
        rotateImg(img, "right", canvas);
        break;
    }
  }
  //进行最小压缩
  const b64 = canvas.toDataURL("image/jpeg", 0.2);
  console.log("压缩前：" + initSize);
  console.log("compress => compress => b64 ", b64);
  console.log("压缩后base64：" + b64.length);
  console.log(
    "压缩率：" + ~~((100 * (initSize - b64.length)) / initSize) + "%"
  );
  tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
  return b64;
}


/**
 * 使用示例
 */
//1、获取压缩结果 base64
// imgPreview(imgFile, 100, (urlData) => {
     //2、base64转为blob
//   const blobData = base64UrlData2Bolb(urlData);
     //3、blob转为文件
//   const compressFile_ = new File([blobData], name);
//   const params = new FormData(); // 声明formData数据类型
//   params.append("file", compressFile_);
     //4、调用接口上传
//   uploadFileApi(params)
//     .then((res) => {
//       if (res.code == 200) {
//         //5、上传成功
//       } else {
//         fileList.value = [];
//       }
//     })
//     .catch(() => {
//       // fileList.value = [];
//     });
// });